﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace MyApp.Utils
{
  public class ProcessUtils
  {
    /// <summary>
    /// 执行一个CMD
    /// </summary>
    /// <param name="fileName">exe 文件名</param>
    /// <param name="param">exe 接收参数</param>
    /// <param name="showWindows">是否显示窗口</param>
    /// <returns>Exit Code</returns>
    public static int StartProcess(string fileName, string param, bool showWindows = false)
    {
      int exitcode = -1;
      ProcessStartInfo si = new ProcessStartInfo();
      si.Arguments = param;
      si.CreateNoWindow = true;
      si.FileName = fileName;
      si.RedirectStandardError = false;
      si.RedirectStandardOutput = false;
      si.UseShellExecute = true;

      if (showWindows)
      {
        si.WindowStyle = ProcessWindowStyle.Hidden;
      }

      Process psExec = null;

      try
      {
        psExec = Process.Start(si);
        //psExec.WaitForExit();
        //exitcode = psExec.ExitCode;
        exitcode = 0;
      }
      catch (Exception ex)
      {
        Console.WriteLine("Error: " + ex.Message);
        return exitcode;
      }
      finally
      {
        //if (psExec != null)
          //psExec.Close();
      }
      return exitcode;
    }
    /// <summary>
    /// 判断Process是否存在
    /// </summary>
    /// <param name="processName">进程的名称</param>
    /// <returns>true or false</returns>
    public static bool IsExist(string processName)
    {
      bool isRunning = false;
      Process[] pList = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(processName));
      if (pList != null && pList.Length > 0)
      {
        isRunning = true;
      }
      return isRunning;    
    }
    /// <summary>
    /// 查找一个Process对象，默认只返回第一个找到的
    /// </summary>
    /// <param name="processName">进程名称</param>
    /// <returns>Process</returns>
    public static Process FindOne(string processName) 
    {
      Process[] pList = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(processName)); 
      if(pList != null && pList.Length > 0)
      {
        return pList[0];
      }
      return null;
    }
    /// <summary>
    /// 强制杀掉一个进程
    /// </summary>
    /// <param name="processName">进程名称</param>
    /// <returns>true or false</returns>
    public static bool Kill(string processName)
    {
      try
      {
        Process process = FindOne(processName);
        if(process != null)
        {
          process.Kill();
        }
        return true;
      }
      catch(Exception e)
      {
        return false;
      }      
    }
  }
}
